package com.bsoft.template.service.assets;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bsoft.template.common.Result;
import com.bsoft.template.common.ResultCodeEnum;
import com.bsoft.template.common.auth.UserInfo;
import com.bsoft.template.entity.assets.AssetsZj;
import com.bsoft.template.entity.auth.User;
import com.bsoft.template.entity.process.Process;
import com.bsoft.template.entity.system.Dic;
import com.bsoft.template.entity.system.DicDetails;
import com.bsoft.template.mapper.assets.AssetsZjMapper;
import com.bsoft.template.mapper.auth.UserMapper;
import com.bsoft.template.mapper.system.DicMapper;
import com.bsoft.template.service.base.BaseServiceImpl;
import com.bsoft.template.service.process.ProcessService;
import com.bsoft.template.util.RequestParamPaser;
import com.bsoft.template.util.excel.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AssetsZjService extends BaseServiceImpl<AssetsZjMapper, AssetsZj> {

    @Autowired
    private ProcessService processService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DicMapper dicMapper;

    @Autowired
    private UserInfo userInfo;

    public String getMaxId(String date) {
       return baseMapper.getMaxId(date);
    }

    public Result getList(Map<String, String> params) {
        Result result = new Result();

        Page<AssetsZj> page = new Page<>(
                Long.parseLong(params.getOrDefault("page", "1")),
                Long.parseLong(params.getOrDefault("pageSize", "10"))
        );

        String role = userInfo.getRoleCode();
        List<Process> processes = processService.getProcessList();
        int index = 0;
        for (int i = 0; i < processes.size(); i++) {
            if (processes.get(i).getRole().equals(role)) {
                index = i;
                break;
            }
        }
        params.put("role", role);
        params.put("first", processes.get(0).getRole());
        params.put("last", processes.get(processes.size() - 1).getRole());
        if (index > 0) {
            params.put("previous", processes.get(--index).getRole());
        }

        IPage<AssetsZj> iPage = baseMapper.getList(page, params);

        result.code(ResultCodeEnum.OK.getCode())
                .message("查询成功")
                .data(iPage.getRecords())
                .total(iPage.getTotal());
        return result;
    }

    public Result getAuditCount() {
        String role = userInfo.getRoleCode();
        List<Process> processes = processService.getProcessList();
        int index = 0;
        for (int i = 0; i < processes.size(); i++) {
            if (processes.get(i).getRole().equals(role)) {
                index = i;
                break;
            }
        }
        String previousRole = "";
        if (index > 0) {
            previousRole = processes.get(--index).getRole();
        }
        Map<String, String> map = new HashMap<>();
        List<AssetsZj> list = baseMapper.getList(map);
        String finalPreviousRole = previousRole;
        long count;
        if ("dandang".equals(role)) {
            count = list.stream().filter(item -> item.getApprovalinfos().size() > 0
                    && "2".equals(item.getApprovalinfos().get(0).getSpzt())).count();
        } else {
            count = list.stream().filter(item -> item.getApprovalinfos().size() > 0
                    && finalPreviousRole.equals(item.getApprovalinfos().get(0).getSpjs())
                    && "1".equals(item.getApprovalinfos().get(0).getSpzt())).count();
        }

        if ("fuzong".equals(role)) {
            QueryWrapper<AssetsZj> wrapper = new QueryWrapper<>();
            wrapper.eq("zt", "05");
            Integer num = baseMapper.selectCount(wrapper);
            count += num;
        }

        return new Result().ok().data(count);
    }

    public Result getExpire() {
        QueryWrapper<AssetsZj> wrapper = new QueryWrapper<>();
        wrapper.eq("zt", "02");
        List<AssetsZj> list = baseMapper.selectList(wrapper);
        Date current = new Date();
        long num = list.stream().filter(item -> (item.getHtjsrq().getTime() - current.getTime()) / (1000 * 60 * 60 * 24) <= 30
                && item.getHtjsrq().getTime() - current.getTime() >= 0)
                .collect(Collectors.groupingBy(item -> item.getCfd() + item.getFjh()))
                .size();
        return new Result().ok().data(num);
    }

    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String fjh = request.getParameter("fjh");
        String cfd = request.getParameter("cfd");

        if (StringUtils.isAnyBlank(fjh, cfd)) {
            return;
        }

        QueryWrapper<AssetsZj> wrapper = new QueryWrapper<>();
        wrapper.eq("cfd", cfd)
                .eq("fjh", fjh)
                .orderByDesc("zdrq");
        List<AssetsZj> assetsZjs = baseMapper.selectList(wrapper);

        List<User> users = userMapper.getAllUser();
        List<Dic> dics = dicMapper.getAllDic();

        Map<String, Object> userDic = new HashMap<>();
        for (User user : users) {
            if (user.getPerson() != null) {
                userDic.put(user.getUsername(), user.getPerson().getPersonName());
            } else {
                userDic.put(user.getUsername(), "");
            }

        }

        Map<String, Object> lbDic = new HashMap<>();
        Map<String, List<DicDetails>> mcDic = new HashMap<>();
        for (Dic dic : dics) {
            lbDic.put(dic.getCode(), dic.getName());
            mcDic.put(dic.getCode(), dic.getDicDetails());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");

        List<Map<String,  Object>> list = new ArrayList<>();
        for (AssetsZj assetsZj : assetsZjs) {
            Map<String, Object> item = new HashMap<>();
            item.put("mc", mcDic.get(assetsZj.getZclb()).stream().filter(i -> i.getKey().equals(assetsZj.getMc()))
                    .findFirst().get().getLabel());
            item.put("pp", assetsZj.getPp());
            item.put("ggxh", assetsZj.getGgxh());
            item.put("ccrq", assetsZj.getCcrq() != null ? sdf.format(assetsZj.getCcrq()) : "");
            item.put("gmrq", assetsZj.getGmrq() != null ? sdf.format(assetsZj.getGmrq()) : "");
            item.put("synx", assetsZj.getSynx());
            item.put("sl", assetsZj.getSl());
            item.put("krgs", assetsZj.getKrgs());
            item.put("krxm", assetsZj.getKrxm());
            item.put("fz", assetsZj.getFz());
            item.put("cfd", lbDic.get(assetsZj.getCfd()));
            item.put("fjh", mcDic.get(assetsZj.getCfd()).stream().filter(i -> i.getKey().equals(assetsZj.getFjh()))
                    .findFirst().get().getLabel());
            item.put("htqx", sdf.format(assetsZj.getHtksrq()) + "-" + sdf.format(assetsZj.getHtjsrq()));
            item.put("dwfzr", userDic.get(assetsZj.getDwfzr()));
            item.put("jbr", userDic.get(assetsZj.getJbr()));
            item.put("zdrq", sdf.format(assetsZj.getZdrq()));
            item.put("zdr", userDic.get(assetsZj.getZdr()));
            item.put("dedd", userDic.get(assetsZj.getDedd()));
            item.put("yybfzr", userDic.get(assetsZj.getYybfzr()));
            item.put("bz", assetsZj.getBz());
            list.add(item);
        }

        ExcelWriter excelWriter = ExcelUtil.writeExcel(response, "中介用表.xlsx", "中介用表", ExcelTypeEnum.XLSX);
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(list, fillConfig, writeSheet);
        Map<String, Object> map = list.get(0);
        List<String> zdrList = list.stream().map(i -> String.valueOf(i.get("zdr"))).collect(Collectors.toList());
        List<String> deddList = list.stream().map(i -> String.valueOf(i.get("dedd"))).collect(Collectors.toList());
        zdrList.addAll(deddList);
        map.put("zdr", zdrList.stream().distinct().collect(Collectors.joining(",")));
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();
    }

    public void exportExcelAll(HttpServletRequest request, HttpServletResponse response) throws IOException {

        Map<String, String> params = RequestParamPaser.getParameters(request);
        List<AssetsZj> assetsZjs = baseMapper.getList(params);

        List<User> users = userMapper.getAllUser();
        List<Dic> dics = dicMapper.getAllDic();

        Map<String, Object> userDic = new HashMap<>();
        for (User user : users) {
            if (user.getPerson() != null) {
                userDic.put(user.getUsername(), user.getPerson().getPersonName());
            } else {
                userDic.put(user.getUsername(), "");
            }

        }

        Map<String, Object> lbDic = new HashMap<>();
        Map<String, List<DicDetails>> mcDic = new HashMap<>();
        for (Dic dic : dics) {
            lbDic.put(dic.getCode(), dic.getName());
            mcDic.put(dic.getCode(), dic.getDicDetails());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");

        List<Map<String,  Object>> list = new ArrayList<>();
        for (AssetsZj assetsZj : assetsZjs) {
            Map<String, Object> item = new HashMap<>();
            item.put("pzh", assetsZj.getPzh());
            item.put("mc", mcDic.get(assetsZj.getZclb()).stream().filter(i -> i.getKey().equals(assetsZj.getMc()))
                    .findFirst().get().getLabel());
            item.put("zclb", lbDic.get(assetsZj.getZclb()));
            item.put("pp", assetsZj.getPp());
            item.put("ggxh", assetsZj.getGgxh());
            item.put("ccrq", assetsZj.getCcrq() != null ? sdf.format(assetsZj.getCcrq()) : "");
            item.put("gmrq", assetsZj.getGmrq() != null ? sdf.format(assetsZj.getGmrq()) : "");
            item.put("synx", assetsZj.getSynx());
            item.put("sl", assetsZj.getSl());
            item.put("krgs", assetsZj.getKrgs());
            item.put("krxm", assetsZj.getKrxm());
            item.put("fz", assetsZj.getFz());
            item.put("cfd", lbDic.get(assetsZj.getCfd()));
            item.put("fjh", mcDic.get(assetsZj.getCfd()).stream().filter(i -> i.getKey().equals(assetsZj.getFjh()))
                    .findFirst().get().getLabel());
            item.put("htksrq", sdf.format(assetsZj.getHtksrq()));
            item.put("htjsrq", sdf.format(assetsZj.getHtjsrq()));
            item.put("dwfzr", userDic.get(assetsZj.getDwfzr()));
            item.put("jbr", userDic.get(assetsZj.getJbr()));
            item.put("zdrq", sdf.format(assetsZj.getZdrq()));
            item.put("zdr", userDic.get(assetsZj.getZdr()));
            item.put("dedd", userDic.get(assetsZj.getDedd()));
            item.put("yybfzr", userDic.get(assetsZj.getYybfzr()));
            item.put("bz", assetsZj.getBz());
            list.add(item);
        }

        ExcelWriter excelWriter = ExcelUtil.writeExcel(response, "中介列表.xlsx", "中介列表", ExcelTypeEnum.XLSX);
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(list, fillConfig, writeSheet);
        excelWriter.finish();
    }
}
